package com.atguigu.reggie.controller;

import com.atguigu.reggie.common.R;
import com.atguigu.reggie.entity.User;
import com.atguigu.reggie.service.UserService;
import com.atguigu.reggie.utils.SMSUtils;
import com.atguigu.reggie.utils.ValidateCodeUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Luo Sheng
 * @school YiBin university
 * @create 2022-10-23 19:37
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送手机短信验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user){
        // 获取手机号
        String phoneNumber = user.getPhone();

        if (StringUtils.isNotEmpty(phoneNumber)){
            // 如果一分钟内发送过短信
            // 生成key
            String key = "phoneNumber_" + phoneNumber + "_templateCode";

            // 判断是否已发过验证码
            ValueOperations valueOperations = redisTemplate.opsForValue();
            if (valueOperations.get(key) != null){
               return R.error("短信已发送");
            }

            // 生成随机的四位验证码
//             String templateCode = ValidateCodeUtils.generateValidateCode(4).toString();
            String templateCode = "5873";
            log.info("code={}",templateCode);

            // 调用阿里云的短信服务发送短信
//             String appCode = "9c5d70cbd62148b7a7f496da3a5eb641";
//             String singleName = "创信";
//             SMSUtils.sendMessage(singleName,appCode,templateCode,phoneNumber);
            // 需要将生成的验证码保存到Session
            // httpSession.setAttribute(phoneNumber,templateCode);

            // 将生成的验证码保存到redis并设置时间
            // 设置验证码60秒过期
            valueOperations.set(key,templateCode,5, TimeUnit.MINUTES);

        }

        return R.success("短信发送成功");
    }

    /**
     * 移动端用户登陆
     * @param map
     * @param session
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        log.info("map:{}",map.toString());

        // 获取手机号
        String phone = map.get("phone").toString();

        // 获取验证码
        String code = map.get("code").toString();
        // 从session中获取保存的验证码
//         String codeInSession = (String)session.getAttribute(phone);

        // 生成redis对应的key
        String key = "phoneNumber_" + phone + "_templateCode";

        // 从redis库中获取验证码
        String codeInRedis = (String) redisTemplate.opsForValue().get(key);

        // 进行验证的比对 (页面提交的验证码和session中保存的验证码比对)StringUtils.isNotEmpty(phone)

        if (StringUtils.isNotEmpty(codeInRedis) && codeInRedis.equals(code)){
            // 如果比对成功，说明登陆成功
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(userLambdaQueryWrapper);
            if (user == null){
                // 判断当前手机号对应的用户是否为型用户，如果是就自动完成注册
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);

            }else if (user.getStatus() == 0){

                    return R.error("该用户已被禁用");

            }
            session.setAttribute("user",user.getId());

            // 删除缓存
            redisTemplate.delete(key);

            return R.success(user);
        }
        return R.error("登陆失败");
    }

    /**
     * 用户登出
     * @return
     */
    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");

        return R.success("成功登出");
    }



}
